package com.dm0858.bianmin.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.amap.api.location.CoordinateConverter;
import com.amap.api.location.DPoint;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dm0858.bianmin.R;
import com.dm0858.bianmin.model.entity.NormalListData;
import com.dm0858.bianmin.model.response.BannerResponse;
import com.dm0858.bianmin.ui.adapter.NormalListAdapter;
import com.dm0858.bianmin.ui.base.BaseActivity;
import com.dm0858.bianmin.ui.base.BasePresenter;
import com.dm0858.bianmin.ui.fragment.HomeFragment;
import com.google.gson.Gson;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends AppCompatActivity {
    private ImageView iv_back;

    ListView searchList;
    WebView webView;
    MyAdapter myAdapter;
    private List<SearchModel.DataBean> madapter_data = new ArrayList<>();


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchone);

        iv_back = findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        searchList = findViewById(R.id.searchList);
        webView = findViewById(R.id.webView);

        myAdapter = new MyAdapter();
        searchList.setAdapter(myAdapter);

        Intent intent = getIntent();
        String json = intent.getStringExtra("json");
        Boolean isWeb = intent.getBooleanExtra("isWeb",false);
        if (isWeb) {
            webView.setVisibility(View.VISIBLE);
            searchList.setVisibility(View.GONE);
            webView.getSettings().setJavaScriptEnabled(true);
            //获得网址
            String wangzhi = "https://www.baidu.com/s?wd=" + json;//也可以写具体的网址
            //加载网址
            webView.loadUrl(wangzhi);
        }else {
            //在这里解析数据
            Gson g = new Gson();
            SearchModel searchModel = g.fromJson(json, SearchModel.class);
            if (searchModel.getStatus().equals("1")) {
                madapter_data = searchModel.getData();
                myAdapter.notifyDataSetChanged();
            }

            searchList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {



                }
            });






        }





    }













    public class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            int count= madapter_data.size();
            return count;
        }

        @Override
        public Object getItem(int arg0) {
            int arg1=arg0;
            return madapter_data.get(arg0);
        }

        @Override
        public long getItemId(int arg0) {
            int arg1=arg0;
            // TODO Auto-generated method stub
            return arg1;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup arg2) {


            MyViewHolder holder = null;


//L.e("screenWidth:" + screenWidth);
            if(convertView == null){
                convertView= LayoutInflater.from(SearchActivity.this).inflate(R.layout.item_normal_list, null);
                holder = new MyViewHolder();
                convertView= LayoutInflater.from(SearchActivity.this).inflate(R.layout.item_normal_list, null);
                holder.fruitImage = (ImageView) convertView.findViewById(R.id.normal_img);//获取该布局内的图片视图
                holder.normal_title = (TextView) convertView.findViewById(R.id.normal_title);//获取该布局内的文本视图
                holder.normal_addr = (TextView) convertView.findViewById(R.id.normal_addr);//获取该布局内的文本视图
                holder.normal_tel = (TextView) convertView.findViewById(R.id.normal_tel);//获取该布局内的文本视图
                holder.normal_beian = (TextView) convertView.findViewById(R.id.normal_beian);//获取该布局内的文本视图
                holder.normal_juli = (TextView) convertView.findViewById(R.id.normal_juli);//获取该布局内的文本视图
                holder.callbtn = (Button) convertView.findViewById(R.id.callbtn);//获取该布局内的文本视图

                convertView.setTag(holder);

            }else {
                holder = (MyViewHolder) convertView.getTag();
            }



//        fruitImage.setImageResource();//为图片视图设置图片资源
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String typeID = madapter_data.get(position).getId();
                    Intent intent = new Intent(getApplication(), ShangJiaActivity.class);
                    intent.putExtra(ShangJiaActivity.id, typeID);
                    intent.putExtra("lat", madapter_data.get(position).getLat());
                    intent.putExtra("lng", madapter_data.get(position).getLng());
                    startActivity(intent);
                }
            });
            RequestOptions options = new RequestOptions();

            options.placeholder(R.drawable.addnews);

            Glide.with(SearchActivity.this).load(madapter_data.get(position).getImage()).apply(options).into(holder.fruitImage);

            //     Glide.with(getContext()).load(madapter_data.get(position).address).into(fruitImage);
            holder.normal_title.setText(madapter_data.get(position).getTitle());//为文本视图设置文本内容
            holder.normal_addr.setText(madapter_data.get(position).getAddr());
            holder.normal_juli.setText(madapter_data.get(position).getJuli());
            if (madapter_data.get(position).getBeian() == null) {
                holder.normal_beian.setVisibility(View.GONE);

            }else {
                holder.normal_beian.setVisibility(View.VISIBLE);
                holder.normal_beian.setText(madapter_data.get(position).getBeian());

            }
            if (madapter_data.get(position).getTel().equals("")) {
                holder.callbtn.setVisibility(View.GONE);
            }else {
                holder.callbtn.setVisibility(View.VISIBLE);
                holder.normal_tel.setText(madapter_data.get(position).getTel());

                holder.callbtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+madapter_data.get(position).getTel()));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        getApplicationContext().startActivity(intent);
                    }
                });

            }


            holder.normal_juli.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转

                    //  com.baidu.BaiduMap这是高德地图的包名
                    //调起百度地图客户端try {
                    Intent intent = new Intent();

                    intent.setData(Uri.parse("baidumap://map/marker?location="
                            + madapter_data.get(position).getLat() + "," + madapter_data.get(position).getLng() + "&title="+ madapter_data.get(position).getAddr() +"&content=&traffic=on&src=andr.baidu.openAPIdemo"));


                    if(isInstallByread("com.baidu.BaiduMap")){
                        getApplicationContext().startActivity(intent); //启动调用
                        Log.e("GasStation", "百度地图客户端已经安装") ;

                    }else{

                        if(isInstallByread("com.autonavi.minimap")){
                            Log.e("GasStation", "高德地图客户端已经安装") ;
                            goToGaode(madapter_data.get(position).getLat(),madapter_data.get(position).getLng());
                        }else{
                            Toast.makeText(getApplicationContext(), "没有安装地图客户端", Toast.LENGTH_SHORT).show();
                        }
                    }
                }

            });
            //Toast.makeText(mContext, "你点击了按钮",Toast.LENGTH_LONG).show();

//            TextView tiametxt = (TextView) convertView.findViewById(R.id.news_time);//获取该布局内的文本视图
//            String timestr = DateUtils.dataOne(madapter_data.get(position).addtime);
//            tiametxt.setText(DateUtils.timedate(timestr));

            return convertView;




        }

        //高德
        private void goToGaode(String lat, String lon) {

            CoordinateConverter converter  = new CoordinateConverter(getApplicationContext());
// CoordType.GPS 待转换坐标类型
            converter.from(CoordinateConverter.CoordType.GPS);
// sourceLatLng待转换坐标点 DPoint类型
            try {
                converter.coord(new DPoint(Double.parseDouble(lat),Double.parseDouble(lon)));
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "解析经纬度出错", Toast.LENGTH_SHORT).show();

                return;
            }
// 执行转换操作
            DPoint desLatLng;

            try {
                desLatLng = converter.convert();
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "解析经纬度出错", Toast.LENGTH_SHORT).show();
                return;
            }

            StringBuffer stringBuffer = new StringBuffer("androidamap://route?sourceApplication=").append("amap");

            stringBuffer.append("&dlat=").append(desLatLng.getLatitude())
                    .append("&dlon=").append(desLatLng.getLongitude())
                    .append("&dname=").append("")
                    .append("&dev=").append(0)
                    .append("&t=").append(0);

            Intent intent = new Intent("android.intent.action.VIEW", android.net.Uri.parse(stringBuffer.toString()));
            intent.setPackage("com.autonavi.minimap");
            getApplicationContext().startActivity(intent);
        }

        /**
         * 判断是否安装目标应用
         * @param packageName 目标应用安装后的包名
         * @return 是否已安装目标应用
         */
        private boolean isInstallByread(String packageName) {
            return new File("/data/data/" + packageName).exists();
        }

        public class MyViewHolder {
            ImageView fruitImage;//获取该布局内的图片视图
            TextView normal_title;//获取该布局内的文本视图
            TextView normal_addr;//获取该布局内的文本视图
            TextView normal_tel;//获取该布局内的文本视图
            TextView normal_beian;//获取该布局内的文本视图
            TextView normal_juli;//获取该布局内的文本视图
            Button callbtn;//获取该布局内的文本视图
            }


    }
}
